using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using Microsoft.Office;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using CSP.Model.Entities;
using Microsoft.SharePoint.Administration;

namespace CSP.Model.DataAccess
{
    public class SPDataAccess
    {
        #region Generic Methods
        public static StringBuilder sb = new StringBuilder();

        public static string getCurrentSiteTitle()
        {
            SPWeb webContext = null;

            try
            {
                webContext = SPContext.Current.Web;
                using (SPSite mySite = new SPSite(webContext.Site.ID))
                {
                    using (SPWeb myWeb = mySite.OpenWeb(webContext.ID))
                    {
                        return myWeb.Title.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                sb.AppendLine("Excepcion [getTitle]: " + ex.ToString());
            }

            return String.Empty;
        }

        public static SPListItemCollection getList(string lstName, SPQuery query)
        {
            SPListItemCollection myCollection = null;
            SPWeb webContext = null;

            try
            {
                webContext = SPContext.Current.Web;
                using (SPSite mySite = new SPSite(webContext.Site.ID))
                {
                    using (SPWeb myWeb = mySite.OpenWeb(webContext.ID))
                    {
                        SPList myList = myWeb.Lists[lstName];
                        myCollection = myList.GetItems(query);
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                //if (webContext != null)
                //    webContext.Dispose();
            }

            return myCollection;
        }

        public static SPListItemCollection getList(string lstName)
        {
            SPListItemCollection myCollection = null;

            SPWeb webContext = null;
            try
            {
                webContext = SPContext.Current.Web;

                using (SPSite mySite = new SPSite(webContext.Site.ID))
                {
                    using (SPWeb myWeb = mySite.OpenWeb())
                    {
                        SPList myList = myWeb.Lists[lstName];
                        myCollection = myList.Items;
                    }
                }

            }
            catch
            {
                throw;
            }
            finally
            {
                //if (webContext != null)
                //    webContext.Dispose();
            }

            return myCollection;
        }

        public static SPListItemCollection getBlogPosts(string blogUrl)
        {
            SPListItemCollection myCollection = null;

            SPWeb webContext = null;
            try
            {
                webContext = SPContext.Current.Web;

                using (SPSite mySite = new SPSite(webContext.Url + blogUrl))
                {

                    using (SPWeb myWeb = mySite.OpenWeb())
                    {
                        SPList myList = myWeb.Lists["Posts"];
                        myCollection = myList.Items;
                    }
                }

            }
            catch (Exception ex)
            {
                sb.AppendLine("Excepcion [getBlogPosts][" + webContext.Url + blogUrl + "][" + webContext.Site.Url + "][" + webContext.ToString() + "][" + SPContext.Current.Web.Url + "][" + SPContext.Current.Web.PortalUrl + "]: " + ex.ToString());
            }
            finally
            {
                if (webContext != null)
                    webContext.Dispose();
            }

            return myCollection;
        }

        public static SPListItemCollection getList(string lstName, string viewName, string siteUrl)
        {
            SPListItemCollection myCollection = null;

            SPWeb webContext = null;

            try
            {
                webContext = SPContext.Current.Web;
                SPSecurity.RunWithElevatedPrivileges(delegate()
               {
                   using (SPSite mySite = new SPSite(siteUrl))
                   {
                       using (SPWeb myWeb = mySite.OpenWeb())
                       {
                           SPList myList = myWeb.Lists[lstName];
                           SPFieldCollection fields = myList.Fields;
                           SPView view = myList.Views[viewName];
                           myCollection = myList.GetItems(view);
                       }
                   }
               });
            }

            catch (Exception ex)
            {
                throw;
            }

            return myCollection;
        }

        public static SPListItem getItem(string lstName, SPQuery query)
        {
            SPListItemCollection myCollection = getList(lstName, query);

            if (myCollection != null)
            {
                try
                {
                    foreach (SPListItem myItem in myCollection)
                    {
                        if (myItem != null)
                            return myItem;
                    }
                }
                catch (Exception ex)
                {
                    sb.AppendLine("Excepcion [getList]: " + ex.ToString());
                }
            }
            return null;
        }

        public static string getItemColumn(string lstName, SPQuery query, string columnName)
        {
            SPListItem myItem = getItem(lstName, query);

            if (myItem != null && myItem[columnName] != null)
            {
                return myItem[columnName].ToString().Trim();
            }

            return string.Empty;
        }

        public static bool addItem(SPWeb myWeb, SPList myList, Dictionary<string, string> item)
        {
            myWeb.AllowUnsafeUpdates = true;

            SPListItemCollection myCollection = myList.Items;
            SPListItem listItem = myCollection.Add();
            foreach (string key in item.Keys)
            {
                if (listItem.Fields.ContainsField(key))
                {
                    listItem[key] = item[key];
                }
            }

            listItem.Update();
            myList.Update();
            myWeb.AllowUnsafeUpdates = false;
            return true;
        }

        public static bool addItem(string _siteUrl, string lstName, Dictionary<string, string> item)
        {

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite mySite = new SPSite(_siteUrl))
                    {
                        using (SPWeb myWeb = mySite.OpenWeb())
                        {
                            myWeb.AllowUnsafeUpdates = true;

                            SPList myList = myWeb.Lists[lstName];
                            SPListItemCollection myCollection = myList.Items;
                            SPListItem listItem = myCollection.Add();

                            foreach (string key in item.Keys)
                            {
                                if (listItem.Fields.ContainsField(key))
                                {
                                    listItem[key] = item[key];
                                }
                            }

                            listItem.Update();
                            myList.Update();
                            myWeb.AllowUnsafeUpdates = false;

                        }
                    }
                });
            }
            catch (Exception ex)
            {
                sb.AppendLine("Excepcion [addItem]: " + ex.ToString());
                return false;
            }
            return true;
        }

        public static bool updateItem(SPWeb myWeb, SPList myList, Dictionary<string, string> item, SPListItem listItem)
        {
            myWeb.AllowUnsafeUpdates = true;

            foreach (string key in item.Keys)
            {
                if (listItem.Fields.ContainsField(key))
                {
                    if (key != "ID")
                    {
                        listItem[key] = item[key];
                    }
                }
            }

            listItem.Update();
            myList.Update();
            myWeb.AllowUnsafeUpdates = false;
            return true;
        }

        public static string generateQueryFilter(IList idsList, Dictionary<string, string> item, int index)
        {
            if (index == 1)
            {
                return
                    "<Eq><FieldRef Name='" + idsList[index - 1] +
                    "' />" + "<Value Type='Text'>" + item[idsList[index - 1].ToString()] +
                    "</Value></Eq>";
            }
            else if (index == 2)
            {
                return "<And>" +
                            "<Eq><FieldRef Name='" + idsList[index - 1] +
                            "' /><Value Type='Text'>" + item[idsList[index - 1].ToString()] +
                            "</Value></Eq>" +
                            "<Eq><FieldRef Name='" + idsList[index - 2] +
                            "' /><Value Type='Text'>" + item[idsList[index - 2].ToString()] +
                            "</Value></Eq>" +
                       "</And>";
            }
            else if (index > 2)
            {
                return "<And>" +
                            generateQueryFilter(idsList, item, index - 1) +
                            "<Eq><FieldRef Name='" + idsList[index - 1] +
                            "' /><Value Type='Text'>" + item[idsList[index - 1].ToString()] +
                            "</Value></Eq>" +
                       "</And>";
            }
            return String.Empty;
        }

        public static bool saveItem(IList idsList, string lstName, Dictionary<string, string> item)
        {
            SPWeb webContext = null;
            try
            {
                webContext = SPContext.Current.Web;
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite mySite = new SPSite(webContext.Site.ID))
                    {
                        using (SPWeb myWeb = mySite.OpenWeb(webContext.ID))
                        {
                            SPQuery query = new SPQuery();
                            StringBuilder strQuery = new StringBuilder("<Where>");
                            strQuery.Append(generateQueryFilter(idsList, item, idsList.Count));
                            strQuery.Append("</Where>");
                            query.Query = strQuery.ToString();

                            SPList myList = myWeb.Lists[lstName];
                            SPListItemCollection myCollection = myList.GetItems(query);

                            if (myCollection != null)
                            {
                                if (myCollection.Count > 0)
                                {
                                    //Update
                                    SPListItem myItem = myCollection[0];
                                    updateItem(myWeb, myList, item, myItem);
                                }
                                else
                                {
                                    //Add                                    
                                    addItem(myWeb, myList, item);
                                }
                            }

                        }
                    }
                });
            }
            finally
            {
                if (webContext != null)
                    webContext.Dispose();
            }

            return true;
        }

        public static void deleteAllItems(string lstName, string siteUrl)
        {
            SPWeb webContext = null;
            SPListItemCollection myCollection = null;

            try
            {
                webContext = SPContext.Current.Web;
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite mySite = new SPSite(siteUrl))
                    {
                        using (SPWeb myWeb = mySite.OpenWeb())
                        {
                            myWeb.AllowUnsafeUpdates = true;
                            SPList myList = myWeb.Lists[lstName];
                            myCollection = myList.Items;
                            foreach (SPListItem item in myCollection)
                            {
                                item.Delete();
                            }
                            //SPListItem item = myCollection.GetItemById(ID);
                            //item.Delete();
                            myWeb.AllowUnsafeUpdates = false;
                        }
                    }
                });
            }

            catch (Exception ex)
            {
                sb.AppendLine("Excepcion [getList]: " + ex.ToString());
            }
            finally
            {

                //if (webContext != null)
                //    webContext.Dispose();
            }

        }

        public static void deleteItem(string listName, string itemId)
        {
            SPWeb webContext = null;

            webContext = SPContext.Current.Web;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite mySite = new SPSite(webContext.Site.ID))
                {
                    using (SPWeb myWeb = mySite.OpenWeb(webContext.ID))
                    {
                        myWeb.AllowUnsafeUpdates = true;
                        SPList myList = myWeb.Lists[listName];
                        SPListItemCollection myCollection = myList.Items;

                        if (myCollection != null)
                        {
                            myCollection.DeleteItemById(Int32.Parse(itemId));
                        }
                        myWeb.AllowUnsafeUpdates = false;
                    }
                }
            });
        }
        #endregion

        #region Tweets
        public static bool addPeepBAK(string lstName, CSP.Model.Entities.Peep peep, string _siteUrl)
        {
            //string _siteUrl = SPContext.Current.Site.Url;   
            //string _siteUrl = "http://localhost:11000/";
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite mySite = new SPSite(_siteUrl))
                    {
                        using (SPWeb myWeb = mySite.OpenWeb())
                        {
                            myWeb.AllowUnsafeUpdates = true;

                            SPList myList = myWeb.Lists[lstName];
                            SPListItemCollection myCollection = myList.Items;
                            SPListItem listItem = myCollection.Add();

                            listItem[4] = peep.User;
                            listItem[1] = peep.Title;
                            listItem[5] = peep.Created;

                            listItem.Update();
                            myList.Update();
                            myWeb.AllowUnsafeUpdates = false;
                        }
                    }
                });
            }
            catch (Exception ex)
            {
            }

            return true;

        }

        public static bool addPeep(string lstName, Dictionary<string, string> item)
        {

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPContext.Current.Web.AllowUnsafeUpdates = true;
                    SPList myList = SPContext.Current.Web.Lists[lstName];
                    SPListItemCollection myCollection = myList.Items;
                    SPListItem listItem = myCollection.Add();
                    foreach (string key in item.Keys)
                    {
                        if (listItem.Fields.ContainsField(key))
                        {
                            listItem[key] = item[key];
                        }
                    }

                    listItem.Update();
                    myList.Update();
                    SPContext.Current.Web.AllowUnsafeUpdates = false;
                });
            }
            catch
            {
                return false;
            }

            return true;

        }

        //public static bool addPeep(string lstName, string _siteUrl, Dictionary<string, string> item)
        //{
        //    try
        //    {
        //        SPSecurity.RunWithElevatedPrivileges(delegate()
        //        {
        //            using (SPSite mySite = new SPSite(_siteUrl))
        //            {
        //                using (SPWeb myWeb = mySite.OpenWeb())
        //                {
        //                    myWeb.AllowUnsafeUpdates = true;

        //                    SPList myList = myWeb.Lists[lstName];
        //                    SPListItemCollection myCollection = myList.Items;
        //                    SPListItem listItem = myCollection.Add();
        //                    foreach (string key in item.Keys)
        //                    {
        //                        if (listItem.Fields.ContainsField(key))
        //                        {
        //                            listItem[key] = item[key];
        //                        }
        //                    }

        //                    listItem.Update();
        //                    myList.Update();
        //                    myWeb.AllowUnsafeUpdates = false;
        //                }
        //            }
        //        });
        //    }
        //    catch
        //    {
        //        return false;
        //    }

        //    return true;

        //}
        #endregion

        #region Colleagues
        public static Microsoft.Office.Server.UserProfiles.UserProfile getProfileData(string uniqueID)
        {
            SPWeb webContext = null;
            UserProfile userProfile = null;

            try
            {
                webContext = SPContext.Current.Web;

                using (SPSite mySite = new SPSite(webContext.Site.ID))
                {
                    ServerContext sContext = ServerContext.GetContext(mySite);
                    UserProfileManager upManager = new UserProfileManager(sContext);
                    userProfile = upManager.GetUserProfile(uniqueID);
                }
            }
            catch
            {
                throw;
            }
            return userProfile;
        }


        public static bool addColleague(string userLogin, string colleagueLogin)
        {
            SPWeb webContext = SPContext.Current.Web;
            try
            {
                //SPUserToken token = user.UserToken;
                using (SPSite site = new SPSite(webContext.Site.ID))
                {
                    //Get Server context
                    ServerContext context = ServerContext.GetContext(site);

                    //Get UserProfileManager for the site cocntext
                    UserProfileManager profileManager = new UserProfileManager(context);


                    if (profileManager.UserExists(userLogin))
                    {
                        UserProfile userProfile = profileManager.GetUserProfile(userLogin);

                        if (profileManager.UserExists(colleagueLogin))
                        {
                            ColleagueManager colleagueManager;
                            UserProfile colleagueProfile;
                            colleagueProfile = profileManager.GetUserProfile(colleagueLogin);
                            colleagueManager = userProfile.Colleagues;
                            SPContext.Current.Web.AllowUnsafeUpdates = true;
                            colleagueManager.Create(colleagueProfile, ColleagueGroupType.General, "General", false, Privacy.Public);
                            SPContext.Current.Web.AllowUnsafeUpdates = false; ;
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }

        }

        public static List<Colleague> getColleagues(string userLogin)
        {
            List<Colleague> colleagues = new List<Colleague>();
            SPWeb webContext = SPContext.Current.Web;

            try
            {
                using (SPSite site = new SPSite(webContext.Site.ID))
                {
                    ServerContext context = ServerContext.GetContext(site);

                    UserProfileManager profileManager = new UserProfileManager(context);
                    UserProfile userProfile;

                    if (profileManager.UserExists(userLogin))
                    {
                        userProfile = profileManager.GetUserProfile(userLogin);

                        foreach (Colleague col in userProfile.Colleagues.GetItems())
                        {
                            colleagues.Add(col);
                        }
                    }
                }
            }
            catch
            {
                throw;
            }

            return colleagues;
        }

        public static void addAsColleague(string listName, string itemId)
        {
            SPWeb webContext = null;

            webContext = SPContext.Current.Web;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite mySite = new SPSite(webContext.Site.ID))
                {
                    using (SPWeb myWeb = mySite.OpenWeb(webContext.ID))
                    {
                        if (mySite.AllowUnsafeUpdates == false)
                            mySite.AllowUnsafeUpdates = true;
                        if (myWeb.AllowUnsafeUpdates == false)
                            myWeb.AllowUnsafeUpdates = true;

                        SPQuery query = new SPQuery();
                        string strQuery = String.Format(
                        "<Where><Eq><FieldRef Name='ID'/><Value Type='Text'>{0}</Value></Eq></Where>", itemId);
                        query.Query = strQuery;

                        //Update the IsAllowed column in Follower Requests list
                        SPList myList = myWeb.Lists[listName];
                        SPListItem myItem = myList.GetItemById(Int32.Parse(itemId));
                        SPUser user = GetUser(myItem, "Follower");
                        myItem.Delete();
                        //myItem["IsAllowed"] = true;
                        //myItem.Update();
                        myList.Update();




                        //Add the user to my Colleagues
                        string colleagueAccount = string.Empty;
                        string[] colleagueAuxArray = new string[2];

                        colleagueAccount = user.LoginName;
                        colleagueAuxArray = colleagueAccount.Split('\\');
                        colleagueAccount = colleagueAuxArray[1];

                        string userAccount = SPContext.Current.Web.CurrentUser.LoginName;
                        colleagueAuxArray = userAccount.Split('\\');
                        userAccount = colleagueAuxArray[1];

                        WriteToFollowerList(colleagueAccount);

                        //addColleague(userAccount, colleagueAccount);
                        //addColleague(colleagueAccount, userAccount);
                        myWeb.AllowUnsafeUpdates = false;
                        mySite.AllowUnsafeUpdates = false;
                    }
                }
            });
        }


        public static void CheckForNewColleagues()
        {
            List<FollowerRequest> followers = new List<FollowerRequest>();
            SPQuery query = new SPQuery();
            string strQuery = String.Format(
            "<Where><Eq><FieldRef Name='IsAllowed'/><Value Type='Text'>{0}</Value></Eq></Where>", "true");
            query.Query = strQuery;
            SPListItemCollection list = SPDataAccess.getList("Follower requests", query);

            SPUser currUser = SPContext.Current.Web.CurrentUser;
            List<Colleague> colls = new List<Colleague>();
            colls = SPDataAccess.getColleagues(currUser.LoginName);


            foreach (SPListItem item in list)
            {
                bool colExists = false;
                SPUser user = GetUser(item, "Follower");
                foreach (Colleague c in colls)
                {
                    if (c.Profile["AccountName"].Value.ToString() == user.LoginName)
                    {
                        colExists = true;
                        break;
                    }
                }
                if (!colExists)
                    addColleague(SPContext.Current.Web.CurrentUser.LoginName, user.LoginName);
            }
        }

        public static void WriteToFollowerList(string colleagueAccount)
        {
            const string FOLLOWER_REQUEST_LIST = "Follower requests";
            string userAcc = string.Empty;  //Passed from the borwser
            string currentLoggedUser = string.Empty;

            SPSite siteColl = null;
            //SPWeb site = null;

            siteColl = SPContext.Current.Site;
            //site = SPContext.Current.Web;

            SPSite site = SPContext.Current.Site;
            ServerContext context = ServerContext.GetContext(site);
            UserProfileManager profileManager = new UserProfileManager(context);
            string siteColUrl = profileManager.MySiteHostUrl + "personal/" + colleagueAccount;
            try
            {
                //if (currentuser != null)
                //    currentLoggedUser = currentuser.LoginName;

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    string currentUserLogin = SPContext.Current.Web.CurrentUser.LoginName;
                    string currentUserName = SPContext.Current.Web.CurrentUser.Name;
                    string currentUserEmail = SPContext.Current.Web.CurrentUser.Email;
                    using (SPSite ElevatedsiteColl = new SPSite(siteColUrl))
                    {
                        using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb())
                        {
                            if (ElevatedSite == null || ElevatedSite.Lists == null)
                                return;

                            //IMPORTANT: Allow update to the database.
                            ElevatedSite.AllowUnsafeUpdates = true;

                            SPList idList = ElevatedSite.Lists[FOLLOWER_REQUEST_LIST];
                            SPListItem listItemAdd = idList.Items.Add();


                            if (ElevatedSite.AllUsers[currentUserLogin] == null)
                                ElevatedSite.AllUsers.Add(currentUserLogin, currentUserEmail, currentUserName, "");


                            //       SPFieldUserValue v = new SPFieldUserValue(SPContext.Current.Web, 
                            listItemAdd["Follower"] = ElevatedSite.AllUsers[currentUserLogin]; ;
                            listItemAdd["IsAllowed"] = "true";
                            listItemAdd.Update();
                        }
                    }
                });

            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        private static SPUser GetUser(SPListItem item, string fieldDisplayName)
        {
            //get field and cast to User Field type   

            var field = item.Fields.GetField(fieldDisplayName) as SPField;

            if (field == null)
            {

                throw new ApplicationException("This field is not a User!");
            }

            var fieldValue = field.GetFieldValue(item[field.Id].ToString()) as SPFieldUserValue;

            if (null == fieldValue)
            {
                return null;
            }

            return fieldValue.User;
        }
        #endregion

        #region Updates

        //private static UserChange GetDocumentUpdates(string userAccountName)
        //{
        //    UserChange userDocChange = new UserChange();
        //    //SPSite siteCollection = SPContext.Current.Site;
        //    SPWeb site = SPContext.Current.Web;

        //    //SPWebApplication webApp = SPContext.Current.Site.WebApplication;
        //    //SPSiteCollection siteCollection = webApp.Sites;
        //    //SPSite spsite = siteCollection[0];
        //    //SPWebCollection websites = spsite.AllWebs;


        //    //foreach (SPWeb site in websites)
        //    //{
        //    SPListCollection lists = site.Lists;
        //    SPRegionalSettings regionSettings = site.RegionalSettings;
        //    SPTimeZone timeZone = regionSettings.TimeZone;

        //    SPChangeToken token = new SPChangeToken(SPChangeCollection.CollectionScope.Site, site.ID, DateTime.Today.Subtract(TimeSpan.FromDays(10)));
        //    SPChangeQuery query = new SPChangeQuery(true, true);

        //    SPChangeCollection changes = site.GetChanges(query);
        //    foreach (SPChange changedObject in changes)
        //    {
        //        switch (changedObject.GetType().ToString())
        //        {
        //            case "Microsoft.SharePoint.SPChangeItem":
        //                SPChangeItem changedItem = (SPChangeItem)changedObject;
        //                try
        //                {
        //                    if ((userAccountName.ToLower() == lists[changedItem.ListId].GetItemByUniqueId(changedItem.UniqueId)["Created By"].ToString()
        //                        //|| userAccountName == lists[changedItem.ListId].GetItemByUniqueId(changedItem.UniqueId)["Updated By"].ToString()
        //                        //|| userAccountName == lists[changedItem.ListId].GetItemByUniqueId(changedItem.UniqueId)["Deleted By"].ToString()
        //                         ))
        //                    {
        //                        if ((string.Compare(lists[changedItem.ListId].Title, "User Information List") == 0 && changedItem.ChangeType == SPChangeType.MemberAdd) ||
        //                      ((string.Compare(lists[changedItem.ListId].Title, "User Information List") != 0) &&
        //                       (string.Compare(lists[changedItem.ListId].Title, "Web Part Gallery") != 0) &&
        //                       (string.Compare(lists[changedItem.ListId].Title, "Master Page Gallery") != 0) &&
        //                       (string.Compare(lists[changedItem.ListId].Title, "Reporting Templates") != 0) &&
        //                       (string.Compare(lists[changedItem.ListId].Title, "Reporting Metadata") != 0) &&
        //                       (string.Compare(lists[changedItem.ListId].GetItemByUniqueId(changedItem.UniqueId).Name, "Get Started with Windows SharePoint Services!") != 0)))
        //                        {

        //                            userDocChange.documentNameChange = lists[changedItem.ListId].GetItemByUniqueId(changedItem.UniqueId).Name;
        //                            if (!string.IsNullOrEmpty(userDocChange.documentNameChange) && userDocChange.documentNameChange.ToLower() != "xsl style sheets")
        //                            {
        //                                userDocChange.changeDate = timeZone.LocalTimeToUTC(changedItem.Time);
        //                                userDocChange.UserChangeType = UserChange.UserChangeTypes.DocumentChange;

        //                                switch (changedItem.ChangeType)
        //                                {
        //                                    case SPChangeType.Add:
        //                                        userDocChange.DocumentChangeType = UserChange.DocumentChangeTypes.Added;
        //                                        break;
        //                                    case SPChangeType.Delete:
        //                                        userDocChange.DocumentChangeType = UserChange.DocumentChangeTypes.Deleted;
        //                                        break;
        //                                    case SPChangeType.Update:
        //                                        userDocChange.DocumentChangeType = UserChange.DocumentChangeTypes.Updated;
        //                                        break;
        //                                }
        //                            }
        //                        }

        //                    }
        //                }
        //                catch (Exception ex)
        //                {
        //                    string error = ex.Message;
        //                    //throw new Exception("The object to which item " + changedItem.UniqueId + " belongs does not exist.<BR>");
        //                }
        //                break;
        //        }
        //    }
        //    //}
        //    return userDocChange;
        //}


        private static UserChangeCollection GetDocumentUpdates(UserProfile m_objProfileLoaded)
        {
            UserChange userDocChange = new UserChange();
            UserChangeCollection col = new UserChangeCollection();
            // SPSecurity.RunWithElevatedPrivileges(delegate()
            //{
            //    using (SPSite site = new SPSite(ConfigurationManager.AppSettings["NcorpUrl"]))

            string siteUrl = m_objProfileLoaded.ProfileManager.MySiteHostUrl + "personal/" + m_objProfileLoaded["UserName"].Value.ToString();
            //using (SPSite site = m_objProfileLoaded.PersonalSite)
            using(SPSite site = new SPSite(siteUrl))
            {

                SPListCollection collLists = site.RootWeb.Lists;

                SPRegionalSettings oRegionSettings = site.RootWeb.RegionalSettings;
                SPTimeZone oTimeZone = oRegionSettings.TimeZone;
                DateTime myDate = DateTime.Now.AddDays(-3).ToLocalTime();
                if (myDate < site.WebApplication.Sites[0].RootWeb.Created.ToLocalTime())
                {
                    myDate = site.WebApplication.Sites[0].RootWeb.Created.ToLocalTime();
                }
                SPChangeQuery oQuery = CreateSPChangeQuery(new SPChangeToken(SPChangeCollection.CollectionScope.Site, site.ID, myDate));
                SPChangeCollection collChanges = null;
                try
                {
                    collChanges = site.GetChanges(oQuery);
                }
                catch (Exception)
                {

                    SPChangeToken token = null;
                    oQuery = CreateSPChangeQuery(null);
                    collChanges = site.GetChanges(oQuery);
                }
            


                foreach (SPChange oChange in collChanges)
                {
                    switch (oChange.GetType().ToString())
                    {
                        case "Microsoft.SharePoint.SPChangeItem":
                            SPChangeItem oChangedItem = (SPChangeItem)oChange;
                            try
                            {
                                try
                                {
                                    if (collLists[oChangedItem.ListId] == null)
                                        continue;
                                }
                                catch
                                {
                                    continue;
                                }


                                if (collLists[oChangedItem.ListId].Title.IndexOf("Shared") > -1 || collLists[oChangedItem.ListId].Title.IndexOf("Personal") > -1)
                                {
                                    userDocChange.changeDate = oChangedItem.Time.ToLocalTime();//oTimeZone.LocalTimeToUTC(oChangedItem.Time);
                                    userDocChange.UserChangeType = UserChange.UserChangeTypes.DocumentChange;
                                    userDocChange.documentNameChange = "<a href='" + collLists[oChangedItem.ListId].DefaultViewUrl + "'>" + collLists[oChangedItem.ListId].Title + "</a>";
                                    //collLists[oChangedItem.ListId].Title;

                                    if (m_objProfileLoaded["PictureURL"].Value == null)
                                        userDocChange.colleaguePictureUrl = "/_layouts/images/no_pic.gif";
                                    else
                                        userDocChange.colleaguePictureUrl = m_objProfileLoaded["PictureURL"].Value.ToString();

                                    string firstName = m_objProfileLoaded["FirstName"].Value != null ? m_objProfileLoaded["FirstName"].Value.ToString() : "";
                                    string lastName = m_objProfileLoaded["LastName"].Value != null ? m_objProfileLoaded["LastName"].Value.ToString() : "";

                                    userDocChange.UserNameChange = string.Format("{0} {1}", firstName, lastName);
                                    userDocChange.colleagueNameChange = m_objProfileLoaded["AccountName"].Value.ToString();
                                    switch (oChangedItem.ChangeType)
                                    {
                                        case SPChangeType.Add:
                                            userDocChange.DocumentChangeType = UserChange.DocumentChangeTypes.Added;
                                            break;
                                        case SPChangeType.Delete:
                                            userDocChange.DocumentChangeType = UserChange.DocumentChangeTypes.Deleted;
                                            break;
                                        case SPChangeType.Update:
                                            userDocChange.DocumentChangeType = UserChange.DocumentChangeTypes.Updated;
                                            break;
                                    }
                                    bool exists = false;
                                    foreach (UserChange u in col)
                                    {
                                        if (u.changeDate == userDocChange.changeDate && u.documentNameChange == userDocChange.documentNameChange)
                                        {
                                            exists = true;
                                            break;
                                        }
                                    }
                                    if (exists)
                                        continue;
                                    col.Add(userDocChange);

                                }
                            }
                            catch (Exception ex)
                            {
                                //Response.Write("The object to which item " +
                                //oChangedItem.UniqueId +
                                //" belongs does not exist.<BR>");
                            }
                            break;
                    }
                }

                col.SortColumn = "changeDate";
                col.SortingOrder = GenericComparer.SortOrder.Descending;
                col.Sort();
                return col;
            }
        }


        private static UserChangeCollection GetMyDocumentUpdates(UserProfile m_objProfileLoaded)
        {
            UserChange userDocChange = new UserChange();
            UserChangeCollection col = new UserChangeCollection();
            // SPSecurity.RunWithElevatedPrivileges(delegate()
            //{
            //    using (SPSite site = new SPSite(ConfigurationManager.AppSettings["NcorpUrl"]))
            using (SPSite site = m_objProfileLoaded.PersonalSite)
            {

                SPListCollection collLists = site.RootWeb.Lists;

                SPRegionalSettings oRegionSettings = site.RootWeb.RegionalSettings;
                SPTimeZone oTimeZone = oRegionSettings.TimeZone;

                DateTime myDate = DateTime.Now.AddDays(-3).ToLocalTime();
                if (myDate < site.WebApplication.Sites[0].RootWeb.Created.ToLocalTime())
                {
                    myDate = site.WebApplication.Sites[0].RootWeb.Created.ToLocalTime();
                }
                SPChangeQuery oQuery = CreateSPChangeQuery(new SPChangeToken(SPChangeCollection.CollectionScope.Site, site.ID, myDate));

                SPChangeCollection collChanges = site.GetChanges(oQuery);

                foreach (SPChange oChange in collChanges)
                {
                    switch (oChange.GetType().ToString())
                    {
                        case "Microsoft.SharePoint.SPChangeItem":
                            SPChangeItem oChangedItem = (SPChangeItem)oChange;
                            try
                            {
                                try
                                {
                                    if (collLists[oChangedItem.ListId] == null)
                                        continue;
                                }
                                catch
                                {
                                    continue;
                                }


                                if (collLists[oChangedItem.ListId].Title.IndexOf("Shared") > -1 || collLists[oChangedItem.ListId].Title.IndexOf("Personal") > -1)
                                {
                                    userDocChange.changeDate = oTimeZone.LocalTimeToUTC(oChangedItem.Time);
                                    userDocChange.UserChangeType = UserChange.UserChangeTypes.DocumentChange;
                                    userDocChange.documentNameChange = "<a href='" + collLists[oChangedItem.ListId].DefaultViewUrl + "'>" + collLists[oChangedItem.ListId].Title + "</a>";
                                    //collLists[oChangedItem.ListId].Title;

                                    if (m_objProfileLoaded["PictureURL"].Value == null)
                                        userDocChange.colleaguePictureUrl = "/_layouts/images/no_pic.gif";
                                    else
                                        userDocChange.colleaguePictureUrl = m_objProfileLoaded["PictureURL"].Value.ToString();

                                    string firstName = m_objProfileLoaded["FirstName"].Value != null ? m_objProfileLoaded["FirstName"].Value.ToString() : "";
                                    string lastName = m_objProfileLoaded["LastName"].Value != null ? m_objProfileLoaded["LastName"].Value.ToString() : "";

                                    userDocChange.UserNameChange = string.Format("{0} {1}", firstName, lastName);
                                    userDocChange.colleagueNameChange = m_objProfileLoaded["AccountName"].Value.ToString();
                                    switch (oChangedItem.ChangeType)
                                    {
                                        case SPChangeType.Add:
                                            userDocChange.DocumentChangeType = UserChange.DocumentChangeTypes.Added;
                                            break;
                                        case SPChangeType.Delete:
                                            userDocChange.DocumentChangeType = UserChange.DocumentChangeTypes.Deleted;
                                            break;
                                        case SPChangeType.Update:
                                            userDocChange.DocumentChangeType = UserChange.DocumentChangeTypes.Updated;
                                            break;
                                    }


                                    col.Add(userDocChange);

                                }
                            }
                            catch (Exception ex)
                            {

                            }
                            break;
                    }
                }

                col.SortColumn = "changeDate";
                col.SortingOrder = GenericComparer.SortOrder.Descending;
                col.Sort();
                return col;
            }
        }

        private static SPChangeQuery CreateSPChangeQuery(SPChangeToken myToken)
        {
            SPChangeQuery query = new SPChangeQuery(false, false);

            query.ChangeTokenStart = myToken;
            query.Add = true;
            query.Alert = false;
            query.ContentType = false;
            query.Delete = false;
            query.Field = false;
            query.File = false;
            query.Group = false;
            query.GroupMembershipAdd = false;
            query.Item = true;
            query.List = false;
            query.Move = false;
            query.Navigation = false;
            query.Rename = false;
            query.Restore = false;
            query.RoleAssignmentAdd = false;
            query.RoleAssignmentDelete = false;
            query.RoleDefinitionAdd = false;
            query.RoleDefinitionDelete = false;
            query.RoleDefinitionUpdate = false;
            query.SecurityPolicy = false;
            query.Site = false;
            query.SystemUpdate = false;
            query.Update = false;
            query.User = false;
            query.View = false;
            query.Web = false;

            return query;
        }


        private static Peep FormatPeep(SPListItem item, string userName)
        {

            string title;
            //string user = string.Empty;
            //try
            //{
            //    user = col.Profile["UserName"].Value.ToString();
            //}
            //catch
            //{
            //}
            if (string.IsNullOrEmpty(userName))
                userName = "Anonymous";

            string peepUserImageUrl = GetCurrentUserImage(userName);
            DateTime date;
            string timePosted;
            bool postedToFB = false;
            bool postedToTwitter = false;

            try
            {
                try
                {
                    if (item["PostedToFB"] != null && !string.IsNullOrEmpty(item["PostedToFB"].ToString()))
                    {
                        postedToFB = bool.Parse(item["PostedToFB"].ToString());
                    }
                }
                catch
                {
                }


                if (item["PostedToTwitter"] != null && !string.IsNullOrEmpty(item["PostedToTwitter"].ToString()))
                {
                    postedToTwitter = bool.Parse(item["PostedToTwitter"].ToString());
                    //Fix for old users with invalid postedtoFB column name
                    if (!postedToTwitter) postedToFB = true;
                }


                if (item["Tweet"] != null && item["Tweet"].ToString().Trim() != string.Empty)
                {
                    title = "Posted a new tweet: " + item["Tweet"].ToString();
                }
                else
                {
                    if (postedToTwitter)
                        title = "Posted a new tweet: Welcome to my site!";
                    else
                        title = "Posted a new message: Welcome to my site!";
                }

                if (item["Created"] != null && item["Created"].ToString() != string.Empty)
                {
                    date = DateTime.Parse(item["Created"].ToString());

                    if (DateTime.Compare(DateTime.Now, date) >= 0)
                    {
                        timePosted = FormatPostedTime(date);
                    }
                    else
                    {
                        timePosted = "Posted a while ago";
                    }
                }
                else
                {
                    date = DateTime.Now;
                    timePosted = "Posted a second ago";
                }
            }
            catch (Exception ex)
            {
                string message = ex.StackTrace;
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                return null;
                //throw;
            }

            Peep peep = new Peep(title, userName, date, timePosted, peepUserImageUrl, postedToFB, postedToTwitter);
            return peep;
        }
        public static string FormatPostedTime(DateTime date)
        {
            string timePosted = string.Empty;
            TimeSpan ts = DateTime.Now.Subtract(date);
            timePosted = string.Format("Posted {0} days, {1} hours, {2} minutes ago", ts.Days, ts.Hours, ts.Minutes);
            if (ts.Days <= 0 && ts.Hours <= 0 && ts.Minutes <= 0 && ts.Seconds <= 60)
                timePosted = string.Format("Posted {0} seconds ago", ts.Seconds);
            if (ts.Days <= 0 && ts.Hours <= 0 && ts.Minutes <= 60 && ts.Minutes > 0)
                timePosted = string.Format("Posted {0} minutes ago", ts.Minutes);
            if (ts.Days <= 0 && ts.Hours <= 24 && ts.Hours > 0)
                timePosted = string.Format("Posted {0} hours, {1} minutes ago", ts.Hours, ts.Minutes);
            if (ts.Days > 0)
                timePosted = string.Format("Posted {0} days, {1} hours, {2} minutes ago", ts.Days, ts.Hours, ts.Minutes);

            return timePosted;
        }


        public static List<Peep> GetPeeps(Colleague col, string listName)
        {
            List<Peep> peeps = new List<Peep>();
            SPListItemCollection listItems = null;

            string ColleagueSiteUrl = col.Profile.ProfileManager.MySiteHostUrl + "personal/" + col.Profile["UserName"].Value.ToString();
            try
            {
                using (SPSite colSite = new SPSite(ColleagueSiteUrl))
                {
                    using (SPWeb colWeb = colSite.OpenWeb())
                    {
                        SPList lstTweets = colWeb.Lists[listName];
                        string createdByFieldName = lstTweets.Fields["Created By"].InternalName;
                        SPQuery query = new SPQuery();
                        query.RowLimit = 10;

                        query.Query =
                        "<Query>" +
                            "<Where>" +
                                "<Geq>" +
                                    "<FieldRef Name='Created' />" +
                                    "<Value Type='DateTime'>" +
                                        "<Today OffsetDays='-3' />" +
                                    "</Value>" +
                                 "</Geq>" +
                            "</Where>" +
                        "</Query>";
                        query.ViewFields = "<FieldRef Name='Tweet'/><FieldRef Name='PostedToTwitter'/><FieldRef Name='PostedToFB'/><FieldRef Name='Created'/><FieldRef Name='" + createdByFieldName + " '/>"
                            + "<OrderBy><FieldRef Name='Created' Ascending='FALSE' /></OrderBy>";

                        listItems = colWeb.Lists[listName].GetItems(query);

                    }

                }
            }
            catch (Exception)
            {


            }


            if (listItems != null)
            {
                foreach (SPListItem item in listItems)
                {
                    Peep p = FormatPeep(item, col.Profile["UserName"].Value.ToString());
                    if (p != null)
                        peeps.Add(p);
                }
            }
            return peeps;
        }

        public static List<Peep> GetPeeps(string listName, string siteUrl)
        {
            List<Peep> peeps = new List<Peep>();

            SPListItemCollection listItems = null;



            SPWeb colWeb = SPContext.Current.Site.OpenWeb();

            SPList lstTweets = colWeb.Lists[listName];
            string createdByFieldName = lstTweets.Fields["Created By"].InternalName;
            SPQuery query = new SPQuery();
            query.RowLimit = 10;

            query.Query =
            "<Query>" +
                "<Where>" +
                    "<Geq>" +
                        "<FieldRef Name='Created' />" +
                        "<Value Type='DateTime'>" +
                            "<Today OffsetDays='-5' />" +
                        "</Value>" +
                     "</Geq>" +
                "</Where>" +
            "</Query>";
            query.ViewFields = "<FieldRef Name='Tweet'/><FieldRef Name='PostedToTwitter'/><FieldRef Name='PostedToTwitter'/><FieldRef Name='Created'/><FieldRef Name='" + createdByFieldName + " '/>"
                + "<OrderBy><FieldRef Name='Created' Ascending='FALSE' /></OrderBy>";



            listItems = colWeb.Lists[listName].GetItems(query);


            if (listItems != null && listItems.Count > 0)
            {
                foreach (SPListItem item in listItems)
                {
                    Peep p = FormatPeep(item, SPContext.Current.Web.CurrentUser.Name);
                    if (p != null)
                        peeps.Add(p);
                }
            }

            return peeps;
        }

        private static string GetUserEmail(string userAccount)
        {

            SPWeb oSPWeb = SPContext.Current.Web;
            string email = "";
            try
            {
                if (userAccount == "System Account")
                    return email;
                else
                    return oSPWeb.AllUsers[userAccount].Email;
            }
            catch (Exception)
            {

                return email;
            }

        }

        public static bool CheckIfUserSiteExists(Colleague col)
        {
            bool colleagueSiteExists = false;
            try
            {
                string colleagueSiteUrl = col.Profile.ProfileManager.MySiteHostUrl + "personal/" + col.Profile["UserName"].Value.ToString();
                using (SPSite colSite = new SPSite(colleagueSiteUrl))
                {
                    using (SPWeb colWeb = colSite.OpenWeb())
                    {
                        colleagueSiteExists = colWeb.Exists;
                    }
                }
            }
            catch (Exception ex)
            {
                //Colleague did not create a mysite yet --> site does not exist.
                colleagueSiteExists = false;
            }

            return colleagueSiteExists;
        }


        public static List<UserChange> GetColleagueUpdates()
        {
            SPWeb webContext = null;
            webContext = SPContext.Current.Web;
            SPUser currUser = SPContext.Current.Web.CurrentUser;

            SPWebApplication webApp = SPContext.Current.Site.WebApplication;
            SPSiteCollection siteColl = webApp.Sites;
            string webAppUrl = siteColl[0].Url;


            List<Colleague> colleagues = getColleagues(currUser.LoginName);
            List<UserChange> changes = new List<UserChange>();

            ServerContext serverContext = null;
            UserProfileManager userProfileManager = null;
            using (SPSite mySite = new SPSite(webContext.Site.ID))
            {
                serverContext = ServerContext.GetContext(mySite);
                userProfileManager = new UserProfileManager(serverContext);
            }

            UserProfile userProfile = userProfileManager.GetUserProfile(currUser.LoginName);
            //UserProfile userProfile = userProfileManager.GetUserProfile(col.Profile["AccountName"].Value.ToString());
            PropertyCollection propColl = userProfile.ProfileManager.PropertiesWithSection;

            foreach (Colleague col in colleagues)
            {
                try
                {
                    if (!CheckIfUserSiteExists(col))
                        continue;

                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {

                        using (SPSite mySite = new SPSite(webContext.Site.ID))
                        {
                            using (SPWeb myWeb = mySite.OpenWeb(webContext.ID))
                            {
                                #region Get tweet updates
                                //Peeps
                                List<Peep> peeps = GetPeeps(col, "Tweets");
                                foreach (Peep peep in peeps)
                                {
                                    UserChange userChange = new UserChange();
                                    userChange.changeDate = peep.Created;
                                    userChange.UserNameChange = peep.User;
                                    userChange.blogTitleChange = peep.Title;
                                    userChange.UserChangeType = UserChange.UserChangeTypes.Tweet;
                                    userChange.colleagueEmail = GetUserEmail(peep.User);
                                    string firstName = col.Profile["FirstName"].Value != null ? col.Profile["FirstName"].Value.ToString() : "";
                                    string lastName = col.Profile["LastName"].Value != null ? col.Profile["LastName"].Value.ToString() : "";

                                    userChange.UserNameChange = string.Format("{0} {1}", firstName, lastName);
                                    userChange.colleagueNameChange = col.Profile["AccountName"].Value.ToString();

                                    userChange.colleaguePictureUrl = peep.UserImg;
                                    if (peep.PostedToFB)
                                    {
                                        userChange.blogTitleChange += " <img src='/_layouts/Images/CSP/facebook_small.png' alt='FacebookPost' />";
                                    }
                                    else if (peep.PostedToTwitter)
                                    {
                                        userChange.blogTitleChange += " <img src='/_layouts/Images/CSP/twitter_small.png' alt='TwitterPost' />";
                                    }
                                    if (!string.IsNullOrEmpty(peep.Title))
                                        changes.Add(userChange);
                                }
                                #endregion

                                #region Get Document Updates
                                UserChangeCollection docChangeCol = GetDocumentUpdates(userProfileManager.GetUserProfile(col.Profile["AccountName"].Value.ToString()));
                                foreach (UserChange uc in docChangeCol)
                                {
                                    if (uc.changeDate != DateTime.MinValue)
                                        changes.Add(uc);
                                }

                                #endregion

                                #region Get Blog updates
                                //Peeps
                                List<Blog> blogs = GetUserBlogs(col.Profile, "Posts");
                                foreach (Blog blog in blogs)
                                {
                                    UserChange userChange = new UserChange();
                                    userChange.changeDate = blog.Created;
                                    userChange.UserNameChange = blog.User;
                                    userChange.blogTitleChange = blog.Title;
                                    userChange.UserChangeType = UserChange.UserChangeTypes.Tweet;
                                    userChange.colleagueEmail = GetUserEmail(blog.User);

                                    string firstName = col.Profile["FirstName"].Value != null ? col.Profile["FirstName"].Value.ToString() : "";
                                    string lastName = col.Profile["LastName"].Value != null ? col.Profile["LastName"].Value.ToString() : "";

                                    userChange.UserNameChange = string.Format("{0} {1}", firstName, lastName);
                                    userChange.colleagueNameChange = col.Profile["AccountName"].Value.ToString();

                                    userChange.colleaguePictureUrl = blog.UserImg;

                                    if (!string.IsNullOrEmpty(blog.Title))
                                        changes.Add(userChange);
                                }
                                #endregion
                            }
                        }
                    });

                }
                catch (Exception ex)
                {
                    throw ex;
                }

            }

            #region GetUserProfile changes
            try
            {
                if (userProfile != null && propColl != null)
                {
                    DateTime startDate = DateTime.Today.Subtract(TimeSpan.FromDays(10));

                    UserProfileChangeQuery userProfileChangeQuery = new UserProfileChangeQuery(true, true);
                    UserProfileChangeToken userProfileChangeToken = new UserProfileChangeToken(startDate);

                    userProfileChangeQuery.ChangeTokenStart = userProfileChangeToken;
                    userProfileChangeQuery.UserProfile = true;
                    userProfileChangeQuery.PersonalizationSite = true;
                    userProfileChangeQuery.Update = true;
                    userProfileChangeQuery.Add = true;
                    userProfileChangeQuery.Delete = true;
                    userProfileChangeQuery.SingleValueProperty = true;
                    userProfileChangeQuery.MultiValueProperty = true;
                    userProfileChangeQuery.Colleague = true;
                    userProfileChangeQuery.WebLog = true;
                    userProfileChangeQuery.SiteMembership = true;
                    userProfileChangeQuery.Anniversary = true;

                    //UserProfileChangeCollection userProfileChanges = userProfile.GetColleagueChanges(userProfileChangeQuery);
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        UserProfileChangeDictionary userProfileChangeDictionary = userProfile.GetColleagueChanges(userProfileChangeQuery);
                        foreach (KeyValuePair<long, UserProfileChangeCollection> colUpdates in userProfileChangeDictionary)
                        {
                            //foreach (UserProfileChange change in userProfileChanges)
                            foreach (UserProfileChange change in colUpdates.Value)
                            {
                                UserChange uc = new UserChange();
                                UserProfile colProfile = userProfileManager.GetUserProfile(change.AccountName);

                                string firstName = colProfile["FirstName"].Value != null ? colProfile["FirstName"].Value.ToString() : "";
                                string lastName = colProfile["LastName"].Value != null ? colProfile["LastName"].Value.ToString() : "";

                                uc.UserNameChange = string.Format("{0} {1}", firstName, lastName);
                                uc.colleaguePictureUrl = colProfile["PictureURL"].Value != null ? colProfile["PictureURL"].Value.ToString() : "/_layouts/images/no_pic.gif";
                                uc.colleagueNameChange = colProfile["AccountName"].Value.ToString();
                                uc.colleagueEmail = GetUserEmail(uc.colleagueNameChange);


                                if (change is UserProfileSingleValueChange)
                                {
                                    UserProfileSingleValueChange propChange = (UserProfileSingleValueChange)change;
                                }
                                else if (change is UserProfileMultiValueChange)
                                {
                                    UserProfileMultiValueChange propertyChange = (UserProfileMultiValueChange)change;
                                }
                                else if (change is UserProfileSiteMembershipChange)
                                {
                                    UserProfileSiteMembershipChange smChange = (UserProfileSiteMembershipChange)change;
                                    uc.UserChangeType = UserChange.UserChangeTypes.SiteMembershipChange;
                                    uc.membershipChange = smChange.MemberGroup.DisplayName;
                                    uc.changeDate = smChange.EventTime;

                                    if (uc.changeDate != DateTime.MinValue)
                                        changes.Add(uc);
                                }

                                //else if (change is UserProfileWebLogChange)
                                //{
                                //    UserProfileWebLogChange blogChange = (UserProfileWebLogChange)change;
                                //    uc.UserChangeType = UserChange.UserChangeTypes.BlogChange;
                                //    uc.UserNameChange = blogChange.AccountName;
                                //    uc.blogTitleChange = blogChange.Title;
                                //    uc.blogURLChange = blogChange.PermaLink;
                                //    uc.changeDate = blogChange.EventTime.ToLocalTime();
                                //    uc.colleagueEmail = GetUserEmail(blogChange.AccountName);
                                //    if (uc.changeDate != DateTime.MinValue)
                                //        changes.Add(uc);
                                //}
                                //else if (change is UserProfileColleagueChange)
                                //{
                                //    UserProfileColleagueChange colChange = (UserProfileColleagueChange)change;
                                //    UserProfile col = colChange.Colleague;

                                //    uc.UserChangeType = UserChange.UserChangeTypes.ColleagueChange;
                                //    uc.ColleagueChangeType = (colChange.ChangeType == ChangeTypes.Add ? UserChange.ColleagueChangeTypes.Add : UserChange.ColleagueChangeTypes.Delete);
                                //    string fname = col["FirstName"].Value != null ? col["FirstName"].Value.ToString() : "";
                                //    string lname = col["LastName"].Value != null ? col["LastName"].Value.ToString() : "";
                                //    uc.colleagueNameChange = fname + " " + lname;
                                //    uc.changeDate = colChange.EventTime;

                                //    changes.Add(uc);
                                //}
                                else if (change is UserProfileAnniversaryChange)
                                {
                                    UserProfileAnniversaryChange annivChange = (UserProfileAnniversaryChange)change;
                                    uc.UserChangeType = UserChange.UserChangeTypes.AnniversaryChange;
                                    uc.anniversaryChange = annivChange.Anniversary.ToShortDateString();
                                    uc.changeDate = annivChange.EventTime;

                                    if (uc.changeDate != DateTime.MinValue)
                                        changes.Add(uc);
                                }
                            }

                        }
                    });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            #endregion

            return changes;
        }


        public static string GetCurrentUserImage(string loginname)
        {
            string userImg = string.Empty;

            try
            {
                Microsoft.Office.Server.UserProfiles.UserProfile user = SPDataAccess.getProfileData(loginname);


                if (user["PictureURL"].Value == null)
                    userImg = "/_layouts/images/no_pic.gif";
                else
                    userImg = user["PictureURL"].Value.ToString();

            }
            catch (Exception ex)
            {
                userImg = "/_layouts/images/no_pic.gif";
            }
            return userImg;
        }

        public static List<UserChange> getMyUpdates()
        {
            SPWeb webContext = null;
            webContext = SPContext.Current.Web;
            SPUser currUser = SPContext.Current.Web.CurrentUser;
            List<UserChange> changes = new List<UserChange>();

            try
            {
                using (SPSite mySite = new SPSite(webContext.Site.ID))
                {
                    using (SPWeb myWeb = mySite.OpenWeb(webContext.ID))
                    {

                        ServerContext serverContext = ServerContext.GetContext(mySite);
                        UserProfileManager userProfileManager = new UserProfileManager(serverContext);
                        UserProfile userProfile = userProfileManager.GetUserProfile(currUser.LoginName);
                        PropertyCollection propColl = userProfile.ProfileManager.PropertiesWithSection;

                        if (userProfile != null && propColl != null)
                        {
                            DateTime startDate = DateTime.Today;

                            UserProfileChangeQuery userProfileChangeQuery = new UserProfileChangeQuery(true, true);
                            UserProfileChangeToken userProfileChangeToken = new UserProfileChangeToken(startDate);
                            userProfileChangeQuery.ChangeTokenStart = userProfileChangeToken;
                            userProfileChangeQuery.UserProfile = true;
                            userProfileChangeQuery.PersonalizationSite = true;
                            userProfileChangeQuery.Update = true;
                            userProfileChangeQuery.Add = true;
                            userProfileChangeQuery.Delete = true;
                            userProfileChangeQuery.SingleValueProperty = true;
                            userProfileChangeQuery.MultiValueProperty = true;
                            userProfileChangeQuery.Colleague = true;
                            userProfileChangeQuery.SiteMembership = true;
                            userProfileChangeQuery.Anniversary = true;

                            UserChange uc = new UserChange();


                            SPWebApplication webApp = SPContext.Current.Site.WebApplication;
                            SPSiteCollection siteColl = webApp.Sites;
                            string webAppUrl = siteColl[0].Url;
                            try
                            {
                                List<Peep> peeps = GetPeeps("tweets", webAppUrl);
                                foreach (Peep peep in peeps)
                                {
                                    if (peep.Created > DateTime.Today.Subtract(TimeSpan.FromDays(10)))
                                    {
                                        uc = new UserChange();
                                        uc.changeDate = peep.Created;
                                        uc.UserNameChange = peep.User;
                                        uc.blogTitleChange = peep.Title;
                                        uc.UserChangeType = UserChange.UserChangeTypes.Tweet;
                                        uc.colleagueEmail = GetUserEmail(peep.User);
                                        if (peep.PostedToTwitter)
                                        {
                                            uc.blogTitleChange += " <img src='/_layouts/images/CSP/twitter_small.png' alt='Twitter Post' />";
                                        }
                                        if (peep.PostedToFB)
                                        {
                                            uc.blogTitleChange += " <img src='/_layouts/images/CSP/facebook_small.png' alt='Facebook Post' />";
                                        }

                                        if (!string.IsNullOrEmpty(peep.Title))
                                            changes.Add(uc);
                                    }
                                }
                            }
                            catch (Exception)
                            {
                                
                            }
                            


                            #region Get Document Updates
                            UserChangeCollection docChangeCol = GetDocumentUpdates(userProfileManager.GetUserProfile(userProfile["AccountName"].Value.ToString()));
                            foreach (UserChange uc1 in docChangeCol)
                            {
                                uc1.blogTitleChange = uc1.documentNameChange;

                                if (uc1.changeDate != DateTime.MinValue)
                                    changes.Add(uc1);
                            }

                            #endregion

                            #region Get Blog updates
                            //Peeps
                            List<Blog> blogs = GetUserBlogs(userProfile, "Posts");
                            foreach (Blog blog in blogs)
                            {
                                UserChange userChange = new UserChange();
                                userChange.changeDate = blog.Created;
                                userChange.UserNameChange = blog.User;
                                userChange.blogTitleChange = blog.Title;
                                userChange.UserChangeType = UserChange.UserChangeTypes.Tweet;
                                userChange.colleagueEmail = GetUserEmail(blog.User);

                                string firstName = userProfile["FirstName"].Value != null ? userProfile["FirstName"].Value.ToString() : "";
                                string lastName = userProfile["LastName"].Value != null ? userProfile["LastName"].Value.ToString() : "";

                                userChange.UserNameChange = string.Format("{0} {1}", firstName, lastName);
                                userChange.colleagueNameChange = userProfile["AccountName"].Value.ToString();

                                userChange.colleaguePictureUrl = blog.UserImg;

                                if (!string.IsNullOrEmpty(blog.Title))
                                    changes.Add(userChange);
                            }
                            #endregion



                            UserProfileChangeCollection userProfileChanges = userProfile.GetChanges(userProfileChangeQuery);

                            foreach (UserProfileChange change in userProfileChanges)
                            {
                                uc = new UserChange();
                                uc.UserNameChange = SPContext.Current.Web.CurrentUser.Name;

                                if (change is UserProfileSingleValueChange)
                                {
                                    UserProfileSingleValueChange propChange = (UserProfileSingleValueChange)change;
                                }
                                else if (change is UserProfileMultiValueChange)
                                {
                                    UserProfileMultiValueChange propertyChange = (UserProfileMultiValueChange)change;
                                }
                                //else if (change is UserProfileSiteMembershipChange)
                                //{
                                //    UserProfileSiteMembershipChange smChange = (UserProfileSiteMembershipChange)change;
                                //    uc.UserChangeType = UserChange.UserChangeTypes.SiteMembershipChange;
                                //    uc.membershipChange = smChange.MemberGroup.DisplayName;
                                //    uc.changeDate = smChange.EventTime;

                                //    changes.Add(uc);
                                //}
                                else if (change is UserProfileWebLogChange)
                                {
                                    UserProfileWebLogChange blogChange = (UserProfileWebLogChange)change;
                                    uc.UserChangeType = UserChange.UserChangeTypes.BlogChange;
                                    uc.blogTitleChange = blogChange.Title;
                                    uc.blogURLChange = blogChange.PermaLink;
                                    uc.changeDate = blogChange.EventTime;

                                    changes.Add(uc);
                                }
                                else if (change is UserProfileColleagueChange)
                                {
                                    UserProfileColleagueChange colChange = (UserProfileColleagueChange)change;
                                    UserProfile col = colChange.Colleague;

                                    uc.UserChangeType = UserChange.UserChangeTypes.ColleagueChange;
                                    uc.ColleagueChangeType = (colChange.ChangeType == ChangeTypes.Add ? UserChange.ColleagueChangeTypes.Add : UserChange.ColleagueChangeTypes.Delete);
                                    string fname = col["FirstName"].Value != null ? col["FirstName"].Value.ToString() : "";
                                    string lname = col["LastName"].Value != null ? col["LastName"].Value.ToString() : "";
                                    uc.colleagueNameChange = fname + " " + lname;
                                    uc.changeDate = colChange.EventTime;

                                    changes.Add(uc);
                                }
                                else if (change is UserProfileAnniversaryChange)
                                {
                                    UserProfileAnniversaryChange annivChange = (UserProfileAnniversaryChange)change;
                                    uc.UserChangeType = UserChange.UserChangeTypes.AnniversaryChange;
                                    uc.anniversaryChange = annivChange.Anniversary.ToShortDateString();
                                    uc.changeDate = annivChange.EventTime;

                                    changes.Add(uc);
                                }

                            }
                        }

                    }
                }
            }
            catch
            {
                throw;
            }

            return changes;
        }
        #endregion

        #region Blogs

        public static List<Blog> GetUserBlogs(UserProfile profile, string listName)
        {
            List<Blog> blogs = new List<Blog>();
            SPListItemCollection listItems = null;

            string ColleagueSiteUrl = profile.ProfileManager.MySiteHostUrl + "personal/" + profile["UserName"].Value.ToString() + "/Blog";
            try
            {
                using (SPSite colSite = new SPSite(ColleagueSiteUrl))
                {
                    using (SPWeb colWeb = colSite.OpenWeb())
                    {
                        SPList lstTweets = colWeb.Lists[listName];
                        string createdByFieldName = lstTweets.Fields["Created By"].InternalName;
                        SPQuery query = new SPQuery();
                        query.RowLimit = 10;

                        query.Query =
                        "<Query>" +
                            "<Where>" +
                                "<Geq>" +
                                    "<FieldRef Name='Published' />" +
                                    "<Value Type='DateTime'>" +
                                        "<Today OffsetDays='-3' />" +
                                    "</Value>" +
                                 "</Geq>" +
                            "</Where>" +
                        "</Query>";
                        query.ViewFields = "<FieldRef Name='Title'/><FieldRef Name='Published'/><FieldRef Name='Created'/><FieldRef Name='" + createdByFieldName + " '/>"
                            + "<OrderBy><FieldRef Name='Created' Ascending='FALSE' /></OrderBy>";

                        listItems = colWeb.Lists[listName].GetItems(query);

                    }

                }
            }
            catch (Exception)
            {


            }


            if (listItems != null)
            {
                foreach (SPListItem item in listItems)
                {
                    blogs.Add(FormatBlog(item, profile["UserName"].Value.ToString()));
                }
            }
            return blogs;
        }


        private static Blog FormatBlog(SPListItem item, string userName)
        {

            string title;
            //string user = string.Empty;
            //try
            //{
            //    user = col.Profile["UserName"].Value.ToString();
            //}
            //catch
            //{
            //}
            if (string.IsNullOrEmpty(userName))
                userName = "Anonymous";

            string blogUserImageUrl = GetCurrentUserImage(userName);
            DateTime date;
            string timePosted;


            try
            {


                //if (item["Created By"] != null && item["Created By"].ToString().Trim() != string.Empty)

                ////if (item[9] != null && item[9].ToString().Trim() != string.Empty)
                //{
                //    //DateTime.TryParse(item[9].ToString(),out date);
                //    user = item["Created By"].ToString().Split('#')[1];
                //}
                //else
                //{
                //    user = "Anonymous";
                //}








                if (item["Title"] != null && item["Title"].ToString().Trim() != string.Empty)
                {
                    title = "Posted a new Blog: " + "<a href='/personal/" + userName + "/Blog/default.aspx' >" + item["Title"].ToString() + "</a>";
                }
                else
                {


                    title = "Posted a new Blog: <a href='/personal/" + userName + "/Blog/default.aspx' >Blog Post</a>";
                }

                if (item["Created"] != null && item["Created"].ToString() != string.Empty)
                {
                    date = DateTime.Parse(item["Created"].ToString());

                    if (DateTime.Compare(DateTime.Now, date) >= 0)
                    {
                        timePosted = FormatPostedTime(date);
                    }
                    else
                    {
                        timePosted = "Posted a while ago";
                    }
                }
                else
                {
                    date = DateTime.Now;
                    timePosted = "Posted a second ago";
                }
            }
            catch (Exception ex)
            {
                string message = ex.StackTrace;
                throw;
            }

            Blog blog = new Blog(title, userName, date, timePosted, blogUserImageUrl);
            return blog;
        }
        #endregion
    }
}
